We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Models -> Combining columns from result set into key => value array

In my action controller I have:

$user_groups = UserGroup::find(array('columns' => 'id,label'));
$form = new ProductReviewForm($user_groups);

In the form initialize I have:

public function initialize($user_groups) {

    $user_groups_array = $user_groups->toArray();
    $user_groups_name = array_column($user_groups_array,'id');
    $user_groups_label = array_column($user_groups_array, 'label'); 
    $user_group_options = array_combine($user_groups_name, $user_groups_label);

    $user_group_element = new \Phalcon\Forms\Element\Select("User Group", $user_group_options);
    $user_group_element->setLabel("<label for='User Group' >User Group: </label>");
}

My question? Is there a way to do transform a resultset into an \Phalcon\Forms\Element\Select in less lines?



33.8k
Accepted
answer
edited Jan '15

Maybe:

$form = new ProductReviewForm(UserGroup::find(array('columns' => 'id,label')));

...

public function initialize($user_groups)
{
    $user_group_options = [];

    foreach($user_groups as $userGroup)
    {
        $user_group_options[$userGroup->id] = $userGroup->label;
    }

    $user_group_element = new \Phalcon\Forms\Element\Select("User Group", $user_group_options);
    $user_group_element->setLabel("<label for='User Group' >User Group: </label>");
}


47.7k
edited Jan '15

RompePC - This looks less expensive to me. The way to go. Thanks.



33.8k

Also I think

$user_group_element = new \Phalcon\Forms\Element\Select(
    'User Group',
    UserGroup::find(['columns' => 'id, label']),
    'using' => ['id', 'label']
);

should do the trick.